/**
 * Created by JetBrains WebStorm.
 * User: dimas
 * Date: 16.09.11
 * Time: 23:17
 * To change this template use File | Settings | File Templates.
 */
window.app = new (function(){
    this.colors = [ '#cc0000', '#00cc00', '#0000ff', '#cc00cc', '#cccc00', '#00cccc'];

	/**
	 * enable the color button
	 */
	this.enable = true;
    this.mapDom = null;
    this.map = null;

    /**
     * Array of array of Cell
     * @type Array
     * @return Array
     */
	this.stepCount = 0;
	this.userStep = 0;
	this.score = 10000;
	this.cellsInRegion = 0;
    this.statistic = null;

    /**
     * render buttons
     */
    this.renderButtons = function() {
        var self = this;
        var buttonsPanel = document.getElementById('buttons');
        buttonsPanel.innerHTML = '';
        for (var i = 0; i < this.colors.length; i++) {
            var color = this.colors[i];
            var button = document.createElement('div');
            button.style.backgroundColor = color;
            button.color = color;
            button.onclick = function() {
                self.step(this.color);
            };
            buttonsPanel.appendChild(button);
        }
    }
    
    /**
     * Run first, run once.
     * Call on document.ready
     */
    this.init = function(mapDom){
        var self = this;
        this.map = new MapClass(mapDom);
        this.statistic = new StatisticsClass();
    };

    /**
     * Init cells
     */
    this.initCells = function () {
        this.map.cells = [];
		this.map.mapDom.innerHTML='';
        var rows = this.map.rows;
        var cols = this.map.cols;
        for (var i = 0; i < rows; i++) {
            var a = [];
			var tr = document.createElement('tr');
            for(var j=0; j< cols; j++){
				var dom = document.createElement('td');
				var cell = new CellClass(i,j,dom, this.map);
                a.push(cell);
				tr.appendChild(dom);
				cell.setColor(cell.color);
            }
            this.map.cells.push(a);
			this.map.mapDom.appendChild(tr);
        }
    };

    /**
     * Start new game
     */
    this.start = function(){
		this.enable = true;
        var rows = document.getElementById('rows_count').value;
        var cols = document.getElementById('cols_count').value;
        this.map.rows = parseInt(rows) || 15, document.getElementById('rows_count').value = this.map.rows;
        this.map.cols = parseInt(cols) || 15, document.getElementById('cols_count').value = this.map.cols;
        this.initCells();
        this.renderButtons();
		this.updateUserStep(0);
		this.updateScore(10000);
        this.updateBest();
        this.updateGamesCounts(true);
        this.updateCompletedGamesCounts();
    };

    /**
     *  Step-over game
     */
    this.step = function(color){
		if(!this.enable) return;
		this.stepCount++;
		this.cellsInRegion = 0;
		this.updateUserStep();
        this.map.cells[0][0].changeColor(color, 1, this.stepCount);
		this.updateScore();
		this.checkWin();
        this.updateBest();
    }

    /**
     *  Check win
     */
    this.checkWin = function(){
        var mapSize = this.map.mapSize();
		if(this.cellsInRegion == mapSize){
			var mes = 'You win!';
            //best score
            var bestScore = this.statistic.getBestScore(mapSize);
            this.statistic.setScore(this.score, mapSize);
			if(this.score > bestScore){
                mes += ' Best result!';
            };
			this.enable = false;
            this.updateCompletedGamesCounts(true);
			alert(mes);
		}
    }

    /**
     * set actual best score for current mapSize
     */
    this.updateBest = function(){
        var mapSize = this.map.mapSize();
        document.getElementById('best').innerHTML = this.statistic.getBestScore(mapSize);
    }

    /**
     *  UpdateUserStep
     */
    this.updateUserStep = function(v){
		typeof v == 'number' ? this.userStep = v : this.userStep++;
		document.getElementById('step').innerHTML = this.userStep;
    }

    /**
     *  UpdateScore
     */
    this.updateScore = function(v){
		typeof v == 'number' ? this.score = v : this.score = this.score - Math.floor(this.score * 0.05);
		document.getElementById('score').innerHTML = this.score < 10000 ? this.score : 0;
    }

    /**
     * Started games count
     * @param add - update count
     */
    this.updateGamesCounts = function(update){
        var mapSize = this.map.mapSize();
        var startedGamesCount = this.statistic.getStartedGamesCount(mapSize) || 0;
        document.getElementById('gamesStarted').innerHTML = startedGamesCount;

        if(update)
            this.statistic.addStartedGames(mapSize);
    }
    this.updateCompletedGamesCounts = function(update){
        var mapSize = this.map.mapSize();
        var completedGamesCount = this.statistic.getCompletedGamesCount(mapSize) || 0;
        document.getElementById('gamesCompleted').innerHTML = completedGamesCount;

        if(update)
            this.statistic.addCompletedGames(mapSize);
    }
})();
